package com.codez.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.google.common.collect.Lists;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * 
 * @author 干净的代码
 * @创建时间 ： 2019-07-11
 * 
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement
@ToString
//@XmlType(propOrder= {"id","name"})
public class XmlDemo {

	private Integer id;

	private String name;

	public static void main(String[] args) throws Exception {
		JAXBContext context = JAXBContext.newInstance(XmlDemo.class);
		Marshaller marshaller = context.createMarshaller();

		XmlDemo demo = new XmlDemo(1, "codez");
		demo.setName(null);
		
//		List<XmlDemo> demos = Lists.newArrayList(new XmlDemo(1, "name1"),new XmlDemo(2,"name2"));
		
		marshaller.marshal(demo, new FileOutputStream(new File("d:/demo.xml")));

		SAXReader reader = new SAXReader();
		Document document = reader.read(new FileInputStream(new File("d:/demo.xml")));
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(new FileOutputStream(new File("d:/demo2.xml")), format);
		writer.write(document);
		
		//
		Unmarshaller unmarshaller = context.createUnmarshaller();
		demo = (XmlDemo) unmarshaller.unmarshal(new File("d:/demo.xml"));
		System.out.println(demo);
		
	}

}
